<template>
  <el-drawer v-model="visibeldrawer" direction="rtl">
    <template #header>
      <h4>{{ drawertitle }}</h4>
    </template>
    <template #default>
      <el-form :model="formdata" :rules="rules" label-width="0.4687rem">
        <el-form-item label="文章标题" prop="title">
          <el-input
            v-model="formdata.title"
            placeholder="请输入标题"
          ></el-input>
        </el-form-item>
        <el-form-item label="文章分类" prop="state">
          <ChannelSelect v-model="formdata.classification"></ChannelSelect>
        </el-form-item>
        <el-form-item label="文章封面">
          <el-upload
            :auto-upload="false"
            class="avatar-uploader"
            :show-file-list="false"
            :on-change="onselectfile"
          >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="文章内容" prop="content">
          <!-- 富文本编辑器 -->
          <Toolbar
            style="border: 1px solid #ccc; width: 2.3433rem"
            :editor="editorRef"
            :defaultConfig="toolbarConfig"
            :mode="mode"
          />
          <Editor
            style="
              height: 0.4101rem;
              width: 100%;
              overflow-y: hidden;
              border: 1px #ccc solid;
            "
            v-model="formdata.content"
            :defaultConfig="editorConfig"
            :mode="mode"
            @onCreated="handleCreated"
          />
        </el-form-item>
      </el-form>
    </template>
    <template #footer>
      <div style="flex: auto">
        <el-button type="primary" @click="onpublish('发布')">发布</el-button>
        <el-button @click="onpublish('草稿')">草稿</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup>
import ChannelSelect from '../components/ChannelSelect.vue'
import { reactive, ref, shallowRef, onMounted, onBeforeUnmount } from 'vue'
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { articlepublishservice } from '@/api/article.js'

let imageUrl = ref('')
let formdata = ref({
  articleid: '',
  oldarticleid: '',
  title: '',
  classification: '',
  articlecover: '',
  content: '',
  state: '',
  isedit: false
})
// 转换成formdata格式
let fd = new FormData()
const rules = reactive({
  title: [{ required: true, message: '不能为空', trigger: 'blur' }],
  classification: [{ required: true, message: '不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '不能为空', trigger: 'blur' }],
  state: [{ required: true, message: '不能为空', trigger: 'blur' }]
})
let drawertitle = ref('')
const visibeldrawer = ref(false)
let mode = ref('default')
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
// const valueHtml = ref('<p>hello</p>')
const toolbarConfig = {}
const editorConfig = { placeholder: '输入内容后才能使用上面的工具' }
// 模拟 ajax 异步获取内容
onMounted(() => {
  formdata.value.content = '<p></p>'
})
// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
  editor.focus()
}
defineExpose({
  open: async (row) => {
    visibeldrawer.value = true
    // 每次拉出抽屉时重新赋值formdata
    imageUrl = ref('')
    formdata = ref({
      articleid: '',
      oldarticleid: '',
      title: '',
      classification: '',
      articlecover: '',
      content: '',
      state: '',
      isedit: false
    })
    if (row.articleid) {
      // 文章编辑
      console.log('编辑')
      formdata.value.articleid = row.articleid
      formdata.value.oldarticleid = row.oldarticleid
      imageUrl.value = `http://localhost:9000/${formdata.value.articleid}.jpg`
      drawertitle.value = '文章编辑'
      formdata.value.isedit = true
      formdata.value.title = row.title
      formdata.value.classification = row.classification
      formdata.value.content = row.content
    } else {
      // 添加文章
      formdata.value.isedit = false
      drawertitle.value = '添加文章'
    }
  }
})
const onselectfile = (upload) => {
  imageUrl.value = URL.createObjectURL(upload.raw)
  formdata.value.articlecover = upload.raw
  fd.append('articlecover', upload.raw)
  fd.set('articlecover', upload.raw)
  formdata.value.oldarticleid = formdata.value.articleid
  formdata.value.articleid = upload.raw.uid
}
const onpublish = async (type) => {
  if (type == '发布') {
    // 发布文章  articleid: '',
    formdata.value.state = '发布'
    // append方法会追加,set方法找不到不会赋值,如何值是数组get方法拿不到只能用getall方法
    if (!fd.getAll('articleid')) {
      fd.append('articleid', formdata.value.articleid)
    } else {
      fd.set('articleid', formdata.value.articleid)
    }
    if (!fd.getAll('oldarticleid')) {
      console.log('append')
      fd.append('oldarticleid', formdata.value.oldarticleid)
    } else {
      fd.set('oldarticleid', formdata.value.oldarticleid)
    }
    if (!fd.getAll('title')) {
      fd.append('title', formdata.value.title)
    } else {
      fd.set('title', formdata.value.title)
    }
    if (!fd.getAll('classification')) {
      fd.append('classification', formdata.value.classification)
    } else {
      fd.set('classification', formdata.value.classification)
    }
    if (!fd.getAll('articlecover')) {
      fd.append('articlecover', formdata.value.articlecover)
    } else {
      fd.set('articlecover', formdata.value.articlecover)
    }
    if (!fd.getAll('content')) {
      fd.append('content', formdata.value.content)
    } else {
      fd.set('content', formdata.value.content)
    }
    if (!fd.getAll('state')) {
      fd.append('state', formdata.value.state)
    } else {
      fd.set('state', formdata.value.state)
    }
    if (!fd.getAll('isedit')) {
      fd.append('isedit', formdata.value.isedit)
    } else {
      fd.set('isedit', formdata.value.isedit)
    }

    console.log(fd.getAll('oldarticleid'), 'oldarticleid')
    await articlepublishservice(fd, formdata.value.articleid)
  } else {
    // 草稿
    formdata.value.state = '草稿'
    for (let key in formdata.value) {
      fd.append(key, formdata.value[key])
    }
    await articlepublishservice(fd, formdata.value.articleid)
  }
  visibeldrawer.value = false
  if (formdata.value.isedit == false) {
    // 添加文章,添加完文章后跳到最后一页
    emit('success', 'add')
  } else {
    emit('success', 'edit')
  }
}
const emit = defineEmits(['success'])
</script>

<style scoped lang="less">
.avatar-uploader {
  width: 0.9373rem;
  height: 0.8787rem;
  border: 0.0059rem rgb(196, 195, 195) solid;
  text-align: center;
  line-height: 0.8787rem;
  img {
    width: 0.9373rem;
    height: 0.8787rem;
  }
  i {
    display: block;
    font-size: 0.1172rem;
  }
}
</style>
